package com.woniu.new_orange.personnel_model_wu.controller;

import com.alibaba.druid.util.StringUtils;
import com.woniu.new_orange.entity.User;
import com.woniu.new_orange.personnel_model_wu.Dto.UserDto;
import com.woniu.new_orange.personnel_model_wu.dto.PhoneFrom;
import com.woniu.new_orange.personnel_model_wu.service.UserService;
import com.woniu.new_orange.redis.RedisOps;
import com.woniu.new_orange.util.Result;
import com.woniu.new_orange.util.SendSms;
import com.woniu.new_orange.util.Verify;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Program: new_orange->UserController
 * @Description: 用户表控制层
 * @Author: donghang
 * @Date: 2023-01-14 09:50
 * @Version： 1.0
 **/
@RestController
@RequestMapping("/users")
@Api(tags = "用户")
public class UserController {

    @Autowired
    private SendSms sendSms;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private Verify verify;

    @Autowired
    private UserService userService;

    //  董航  2023/2/6 15:50  用户短信登录
    @PostMapping("/smsLogin")
    public Result smsLogin(@RequestBody PhoneFrom phoneFrom){
        //String massage = redisTemplate.opsForValue().get(phoneFrom.getPhone());
        String massage = (String)RedisOps.getObjectSerialize(phoneFrom.getPhone());
        if ( phoneFrom.getSmsCode() == null) {
            return Result.error().message("输入验证码不能为空！！").code(666);
        } else if(phoneFrom.getSmsCode().equals(massage)){
            User user = userService.loginBySms(phoneFrom.getPhone());
            return Result.ok().data("user",user);
        } else {
            return Result.error().message("登录失败，请稍后再试").code(888);
        }
    }

    //  董航  2023/2/6 14:20  发送用户短信验证码
    @GetMapping("/send/{phone}")
    public Result code(@PathVariable("phone") String phone){
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)){
            return Result.ok();
        }
        //code = UUID.randomUUID().toString().substring(0,4);
        code = UserController.generateCode();
        HashMap<String, Object> param = new HashMap<>();
        param.put("code", code);
        boolean isSend = sendSms.send(phone, "SMS_269130087", param);
        if(isSend){
            RedisOps.setObjectSerialize(phone,code);
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.SECONDS);
            return Result.ok();
        }else{
            return Result.error();
        }
    }


    //  董航  2023/2/1 16:11  用户登录改进版
    @PostMapping("/loginDo")
    public Result toLogin(@RequestBody UserDto userDto){
        if (verify.isEmail(userDto.getUserAccount())) {
            User user = userService.loginByEmail(userDto);
            if (user != null){
                return Result.ok().data("user",user);
            }
        } else if (verify.isMobile(userDto.getUserAccount())){
            User user = userService.loginByPhone(userDto);
            if (user != null){
                return Result.ok().data("user",user);
            }
        } else {
            User user = userService.userLogin(userDto);
            if (user != null){
                return Result.ok().data("user",user);
            }
        }
        return Result.error();
    }
//    注册
@ApiOperation(value = "/用户注册")
@ApiResponses({
        @ApiResponse(code = 401,message = "未认证"),
        @ApiResponse(code = 403,message = "无权访问")
})
    @PostMapping("/add")
    public Result add(@Validated @RequestBody User user){

         int insert = userService.insertSelective(user);
         return Result.ok();
    }
    //修改
    @ApiOperation(value = "/根据userID定位用户")
    @GetMapping("{Id}")
    public Result getOne(@PathVariable long Id){
        User user = userService.selectByPrimaryKey(Id);
        return Result.ok().data("user",user);
    }
    @ApiOperation(value = "/根据userID修改用户信息")
    @PutMapping("")
    public Result update(@RequestBody  User user){
        int i = userService.updateByPrimaryKeySelective(user);
        return Result.ok();
    }

    //  董航  2023/2/6 14:37  随机验证码生成
    public static String generateCode() {
        long codeL = System.nanoTime();
        String codeStr = Long.toString(codeL);
        return codeStr.substring(codeStr.length() - 8, codeStr.length() - 2);
    }
}